package com.xhs.main.controller.yfb;

import com.xhs.main.entity.result.LayuiResponseResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @create 2020-10-24 18:52
 */
@RestController
public class UserController {

    @RequestMapping("/user/login")
    public LayuiResponseResult login(String username, String password, HttpSession session) {
        //根据用户名和密码创建Token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        String msg = null;
        try {
            //获取subject认证主体
            Subject subject = SecurityUtils.getSubject();
            //开始验证。这一步会调到自定义的Realm中。
            subject.login(token);
            System.out.println("登录成功");
            System.out.println(session.getAttribute("user"));
            return new LayuiResponseResult(0, "", 1, null);
        } catch (UnknownAccountException e) {
            msg = "用户名不正确";
        } catch (IncorrectCredentialsException e) {
            msg = "密码不正确";
        } catch (RuntimeException e) {
            msg = "未知错误";
        }
        return new LayuiResponseResult(500, msg, 1, null);
    }

    @RequestMapping("/user/getName")
    public LayuiResponseResult getName(HttpSession session) {
        try {
            return new LayuiResponseResult(0, "", 1, session.getAttribute("user"));
        } catch (RuntimeException e) {
            return new LayuiResponseResult(500, "", 1, null);
        }
    }

}
